﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StandOnTarget : MonoBehaviour {

    BoxCollider2D box;
    Collider2D player;

    [Range(0.9f, 1f)]
    public float checkScale = 1f;

    float half;

    static StandOnTarget current;

    private void Awake() {
        box = GetComponent<BoxCollider2D>();
        half = box.bounds.size.x * checkScale / 2;
    }

    private void FixedUpdate() {

        if (HasPlayer()) {
            if (CanStandOnThis()) {
                StandOnThis();
            } else {
                NotStandOnThis();
            }
        }

    }

    void SetPlayer(Collider2D collision) {
        player = collision;
    }

    bool IsPlayer(Collider2D collision) {
        return collision.gameObject.layer == LayerMask.NameToLayer("Player");
    }

    bool HasPlayer() {
        return player;
    }

    bool CanStandOnThis() {
        float x = player.transform.position.x + player.offset.x * player.transform.localScale.x;
        return x <= transform.position.x + half && x >= transform.position.x - half;
    }

    void StandOnThis() {
        if (transform != player.transform.parent) {
            player.transform.SetParent(transform);
            current = this;
            //Debug.LogWarning(transform.name + " ******StandOnThis");
        }
    }

    void NotStandOnThis() {
        if (transform == player.transform.parent && current == this) {
            player.transform.SetParent(PlayerController.Instance.transform);
            //Debug.LogWarning(transform.name + " ******NotStandOnThis");
        }
    }

    private void OnDestroy() {
        SetPlayer(null);
    }

    private void OnTriggerEnter2D(Collider2D collision) {
        if (IsPlayer(collision)) {
            SetPlayer(collision);
            //Debug.LogWarning(transform.name + " ******Enter");
        }
    }

    private void OnTriggerExit2D(Collider2D collision) {
        if (IsPlayer(collision)) {
            if (HasPlayer()) {
                NotStandOnThis();
            }
            SetPlayer(null);
            //Debug.LogWarning(transform.name + " ******Exit");
        }
    }

#if UNITY_EDITOR
    private void OnDrawGizmos() {
        if (box) {
            float x1 = transform.position.x + box.bounds.size.x * checkScale / 2;
            float x2 = transform.position.x - box.bounds.size.x * checkScale / 2;
            Gizmos.DrawLine(new Vector3(x1, transform.position.y, 0), new Vector3(x2, transform.position.y, 0));
        }

        if (HasPlayer()) {
            float x = player.transform.position.x + player.offset.x * player.transform.localScale.x;
            Gizmos.DrawWireSphere(new Vector3(x, player.transform.position.y, 0), 0.2f);
        }

    }
#endif
}
